import axios from 'axios'
import { localStorage } from './localStorage'
import Vue from "vue"
let loading;
function startLoading() {
  loading = Vue.prototype.$loading({
    lock: true,
    text: "Loading...",
    target: document.querySelector('.main-container')//设置加载动画区域
  });
}
function endLoading() {
  loading.close();
}
//声明一个对象用于存储请求个数
let needLoadingRequestCount = 0;
function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount++;
};
function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
};
// 创建axios实例
const service = axios.create({ withCredentials: true, timeout: 6000 })
//请求
service.interceptors.request.use(config => {
   if(config.data.username && config.data.password){}
   else
     showFullScreenLoading();
    let accessToken = localStorage.get('accessToken')
    config.headers['access_token'] = accessToken
    if (config.headers.access_token) {
        config.headers['access_token'] = config.headers.access_token;
    }
    return config
}, (error) => {
    tryHideFullScreenLoading();
    return Promise.reject(error)
})
//响应
service.interceptors.response.use(
  response => {
        tryHideFullScreenLoading();
        if (response.data.msg === '已退出') {
            window.localStorage.removeItem('accessToken')
        }
        if (response.data.code == 703) {
            alert('你的账户已过期，请重新登陆')
            return window.location.href = "/login"
        }
        if (response.data.user_status == 300) {
            alert('你的账户在别地登陆,请重新登陆')
            return window.location.href = "/login"
        }
        if(response.statusText == "OK"){
          return response
        }
    },
    error => {
      tryHideFullScreenLoading();
      return Promise.reject(error.data)
    }
)
export { service};
